package com.iplay.实战java高并发程序设计.chapter3.c31;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author dangwu
 * @since 2021/10/27 6:06 下午
 */
public class ReenterLockCondition implements Runnable {
    public static ReentrantLock lock = new ReentrantLock();
    public static Condition condition = lock.newCondition();

    @Override
    public void run() {
        lock.lock();
        try {
            //该方法与Object.wait()方法相似，使当前线程等待，同时释放当前锁
            //要求线程持有相关的重入锁，在Condition.await()方法调用后，这个线程会释放这把锁。
            // 同理，在Condition.signal()方法调用时，也要求线程先获得相关的锁。
            condition.await();
            System.out.println("thread is going on");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("come in");
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReenterLockCondition tlc = new ReenterLockCondition();
        Thread t1 =new Thread(tlc);
        t1.start();
        Thread.sleep(2000);
        lock.lock();
        //同理，在Condition.signal()方法调用时，也要求线程先获得相关的锁。
        condition.signal();
        condition.signalAll();
        System.out.println("唤醒了。");
        lock.unlock();
    }
}
